package com.maple.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.maple.entity.Orders;
import com.maple.mapper.OrderMapper;
import com.maple.service.PayNotifyService;
import com.maple.utils.AlipayUtils;
import com.maple.websocket.WebSocketServer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Service
@Slf4j
public class PayNotifyServiceImpl implements PayNotifyService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 支付成功的异步数据处理
     * @param params
     * @return
     */
    @Override
    public boolean paySuccess(Map<String, String> params) {
        // 获取交易状态
        String tradeStatus = params.get("trade_status");
        String outTradeNo = params.get("out_trade_no");
        String totalAmount = params.get("total_amount");

        // 根据交易状态处理业务逻辑
        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
            log.info("Order:{} payment successful, amount:{} ", outTradeNo, totalAmount);
//          封装对象
            Orders orders = new Orders();
            Orders orders1 = orderMapper.queryByOrderId(outTradeNo);
            orders.setId(orders1.getId());
            orders.setStatus(Orders.TO_BE_CONFIRMED);
            orders.setCheckoutTime(LocalDateTime.now());

//            数据库更新
            orderMapper.update(orders);

//            连接数据处理
            Map<Object, Object> map = new HashMap<>();
            map.put("type", 1);
            map.put("orderId", outTradeNo);
            map.put("content", "用户id：" + orders1.getUserId() + ",手机号：" + orders1.getPhone());

//            长连接发送
            String json = JSONUtils.toJSONString(map);
            webSocketServer.sendToAllClient(json);

            return true;
        }else {//验证失败
            return false;
        }
    }
}
